<template>
  <div class="modal">
    <div class="mask" @click="changeIsShowModal(false)"></div>
    <!-- 登录页面 -->
    <div class="loginView">
      <!-- 关闭按钮 -->
      <div class="close" @click="changeIsShowModal(false)">
        <img src="../assets/img/close.png" alt="" />
      </div>

      <!-- 切换登录导航 -->
      <div class="login-nav">
        <a
          href="#"
          :class="{ active: isShowContent }"
          @click="isShowContent = true"
          >手机号登录</a
        >|<a href="#" :class="{ active: !isShowContent }" @click="showQrCode"
          >二维码登录</a
        >
      </div>
      <div class="content">
        <!-- 手机号登录内容 -->
        <div class="phoneLogin" v-show="isShowContent">
          <div class="row">
            <input
              type="text"
              class="ipt"
              placeholder="请输入手机号"
              v-model="phoneNumber"
            />
          </div>
          <!-- 拼图插件 -->
          <div class="row">
            <slide-verify
              :l="42"
              :r="20"
              :w="362"
              :h="140"
              @success="onSuccess"
              @fail="onFail"
              @refresh="onRefresh"
              :style="{ width: '100%' }"
              class="slide-box"
              ref="slideBlock"
              :slider-text="msg"
            ></slide-verify>
          </div>
          <!-- 获取倒计时 -->
          <div class="row">
            <input
              type="text"
              class="ipt"
              placeholder="请输入收集信息验证"
              v-model="code"
            />
            <!-- 切换显示隐藏--二只存一--相反状态 -->
            <button class="msg-btn" v-show="isShowCount" @click="getSMSCode">
              获取验证码
            </button>
            <button class="count-btn" v-show="!isShowCount">
              {{ count }}s
            </button>
          </div>
          <div class="row">
            <button class="login-btn" @click="submitFn">登录</button>
          </div>
        </div>
        <!-- 二维码登录内容 -->
        <div id="weixin" class="codeLogin" v-show="!isShowContent">
          二维码登录
        </div>
      </div>
    </div>
  </div>
</template>

<script>
var timer;
import { mapActions, mapMutations } from "vuex";
import { SMSCodeAPI } from "@/request/api";
import { PhoneLoginAPI } from "@/request/api";
import { BindPhoneAPI } from "@/request/api";
import { userProfilesAPI } from "@/request/api";

export default {
  data() {
    return {
      // 登录内容显示
      isShowContent: true,
      // 滑块显示信息
      msg: "向右滑动",
      // 倒计时显示状态
      isShowCount: true,
      // 倒计时数字
      count: 2,
      // 手机号码
      phoneNumber: "",
      // 验证码
      code: "",
    };
  },

  methods: {
    ...mapMutations({
      changeIsShowModal: "showModal/changeIsShowModal",
      changeIsLogined: "loginStatus/changeIsLogined",
      changeIsShowToast: "showToast/changeIsShowToast",
    }),
    ...mapActions({
      asyncChangeIsShowToast: "showToast/asyncChangeIsShowToast",
      asyncUserInfo: "userInfo/asyncUserInfo",
    }),

    // 封装一个倒计时
    countDown() {
      let timer = setInterval(() => {
        // 倒计时结束初始化状态
        //  1. 分支语句
        if (this.count == 1) {
          clearInterval(timer);
          this.isShowCount = !this.isShowCount;
        } else {
          this.count--;
        }
      }, 1000);
    },

    // 封装一个 非空校验+手机号校验+滑块验证
    toVerify() {
      // 1. 验证手机号是否通过
      // 1.1 手机号非空校验,不通过就停止逻辑执行(return)
      if (!this.phoneNumber) {
        // alert("请输入手机号");
        // 优化弹窗
        this.asyncChangeIsShowToast({
          isShow: true,
          msg: "请输入手机号,手机号不能为空",
          type: "danger",
        });
        return false;
      }
      // 1.2 手机号正则验证,不通过就停止逻辑执行(return)
      let regNumber =
        /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      let res = regNumber.test(this.phoneNumber);
      // alert("请输入正确的手机号码");
      if (!res) {
        // alert("请输入正确的手机号码");
        // 优化弹窗
        this.asyncChangeIsShowToast({
          isShow: true,
          msg: "请输入正确手机号",
          type: "warning",
        });
        return false;
      }
      // 2. 滑块验证,不通过就停止逻辑执行(return)
      if (this.msg == "向右滑动" || this.msg == "再试一次") {
        // alert("滑动滑块到指定位置");
        // 优化弹窗
        this.asyncChangeIsShowToast({
          isShow: true,
          msg: "滑动滑块到指定位置",
          type: "warning",
        });
        return false;
      }
      return true;
    },

    // 获取手机验证码   --- 发送请求(异步函数async--await)
    async getSMSCode() {
      /* // 1. 验证手机号是否通过
        // 1.1 手机号非空校验,不通过就停止逻辑执行(return)
        if (!this.phoneNumber) {
          alert("请输入手机号");
          return;
        }
        // 1.2 手机号正则验证,不通过就停止逻辑执行(return)
        let regNumber =
          /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
        let res = regNumber.test(this.phoneNumber);
        // alert("请输入正确的手机号码");
        if (!res) {
          alert(res, "请输入正确的手机号码");
          return;
        }
        // 2. 滑块验证,不通过就停止逻辑执行(return)
        if (this.msg == "向右滑动" || this.msg == "再试一次") {
          alert("滑动滑块到指定位置");
          return;
        } */

      // 1+2. 非空校验+手机号校验+滑块验证,只要一个验证不通过--就停止逻辑执行(return)
      if (!this.toVerify()) return;

      // 发送注册验证码请求await
      let res = await SMSCodeAPI({ phone: this.phoneNumber.trim() });
      if (!res) return;
      // alert("已发送手机验证信息");

      // 优化弹窗
      this.asyncChangeIsShowToast({
        isShow: true,
        msg: "已发发送获取验证信息请求",
        type: "success",
      });
      if (res.code == 0) {
        // 3.1 倒计时开始
        this.countDown();
        this.isShowCount = !this.isShowCount;
      }
    },

    // 登录
    // 1.
    async submitFn() {
      // 0. 非空校验+手机号校验+滑块验证,只要一个验证不通过--就停止逻辑执行(return)
      // if (!this.toVerify()) return;
      // 1. 验证码非空校验
      if (this.code.trim() == "") {
        // alert("请输入验证码");

        // 优化弹窗
        this.asyncChangeIsShowToast({
          isShow: true,
          msg: "请输入验证码",
          type: "warning",
        });
        return;
      }
      // console.log("发送之前");
      // 2. 发送登录请求
      let uuid = localStorage.getItem("uuid");
      let res = null;
      if (uuid) {
        // 扫描之后407的手机号登录
        res = await BindPhoneAPI({
          phone: this.phoneNumber.trim(),
          verifyCode: this.code.trim(),
          uuid, // es6语法
        });
      } else {
        // 正常的点击登录
        res = await PhoneLoginAPI({
          phone: this.phoneNumber.trim(),
          verifyCode: this.code.trim(),
        });
      }

      if (!res) return;
      // console.log("登录成功", res);
      // 3. 提示登录成功
      // alert("登录成功");
      // 优化弹窗
      this.asyncChangeIsShowToast({
        isShow: true,
        msg: "登录成功",
        type: "success",
      });
      // 4. 保存token值
      localStorage.setItem("x-auth-token", res["x-auth-token"]);
      // 5. 模态框隐藏
      this.changeIsShowModal(false);
      // 6. 购物车显示
      this.changeIsLogined(true);
      // 7. 删除uuid
      localStorage.removeItem("uuid");
      // 8. 登录成功之后,清除code
      this.$router.push(this.$route.path);
      // 9. 发送用户信息请求 -- 携带请求头,同意在篮球器那边处理
      // let uRes = await userProfilesAPI();
      // console.log("用户信息请求:",uRes);
      this.asyncUserInfo();
    },

    // 拼图插件
    // 拼图成功
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "login success, 耗时 " + ms + "s";
    },
    // 拼图失败
    onFail() {
      this.onRefresh(); // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = "再试一次";
    },

    // 微信登录
    showQrCode() {
      this.isShowContent = false;
      //获取二维码 并展示
      // 申请微信登录二维码
      let _this = this;
      new WxLogin({
        id: "weixin",
        appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
        scope: "snsapi_login",
        // 扫码成功后重定向的接口
        redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
        // state填写编码后的url
        state: encodeURIComponent(
          window.btoa("http://127.0.0.1:8080" + _this.$route.path)
        ),
        // 调用样式文件
        href: "data:text/css;base64,LmltcG93ZXJCb3ggLnRpdGxlLC5pbXBvd2VyQm94IC5pbmZvew0KICBkaXNwbGF5OiBub25lOw0KfQ==",
      });
    },
  },
};
</script>

<style lang="less" scoped>
.modal {
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  top: 0;
  .mask {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
  }
  .loginView {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    width: 555px;
    height: 423px;
    background-color: pink;
    background: url("../assets/img/login-box-bg.png");
    .close {
      position: absolute;
      top: 10px;
      right: 60px;
      height: 22px;
      width: 22px;
      cursor: pointer;
    }
    .login-nav {
      display: flex;
      justify-content: center;
      padding-top: 50px;
      font-size: 20px;
      a {
        text-decoration: none;
        color: #999;
        padding: 0 15px;
        &.active {
          color: #333;
        }
      }
    }
    div.content {
      width: 355px;
      margin: 20px auto 0;
      height: 200px;
      .phoneLogin {
        .row {
          display: flex;
          margin-bottom: 20px;
          .ipt {
            flex: 1;
            box-shadow: 0;
            height: 48px;
            padding-left: 10px;
            outline: none;
            box-sizing: border-box;
          }
          button.msg-btn {
            height: 48px;
            margin-left: 2px;
            cursor: pointer;
          }
          button.count-btn {
            width: 82px;
            height: 48px;
            margin-left: 2px;
            cursor: pointer;
          }
          button.login-btn {
            flex: 1;
            height: 48px;
            background-color: #0a328e;
            color: #ddd;
            cursor: pointer;
            border: none;
            font-size: 18px;
          }
        }
      }
      #weixin {
        /* background-color: #fcf; */
        display: flex;
        justify-content: center;
        margin-top: -20px;
      }
    }
  }
}

/deep/.slide-box {
  width: 100%;
  position: relative;
  box-sizing: border-box;
  canvas {
    position: absolute;
    left: 0;
    top: -120px;
    display: none;
    width: 100%;
    box-sizing: border-box;
  }
  .slide-verify-block {
    width: 85px;
    height: 136px;
  }
  .slide-verify-refresh-icon {
    top: -120px;
    display: none;
  }
  &:hover {
    canvas {
      display: block;
    }
    .slide-verify-refresh-icon {
      display: block;
    }
  }
}
</style>
